package giit.computerbase.action;

import giit.computerbase.server.RegisterCodeServer;
import giit.computerbase.util.DealWithCharcter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * User: tum0r
 * Package Name: ${PACKAGE_NAME}
 * Time: 2018-11-30 Friday 10:17:40
 */
public class RegisterCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String user = (String) request.getSession().getAttribute("user");
        boolean isManager = (boolean) request.getSession().getAttribute("manager");
        if (user == null || user.equals("") || !isManager) {
            response.sendRedirect("index");
        }
        String operation = request.getParameter("operation");
        if (operation != null && !operation.equals("")) {
            operation = URLDecoder.decode(operation, "utf-8");
            operation = DealWithCharcter.dealWith(operation);
            RegisterCodeServer registerCodeServer = new RegisterCodeServer();
            switch (operation) {
                case "add":
                    String coutString = request.getParameter("count");
                    int count = 1;
                    if (coutString != null && !coutString.equals("")) {
                        try {
                            count = Integer.parseInt(request.getParameter("count"));
                        } catch (Exception e) {
                            count = 1;
                        }
                    }
                    for (int i = 0; i < count; i++) {
                        registerCodeServer.addCode();
                    }
                    response.sendRedirect("manager.jsp#code");
                    break;
                case "delete":
                    String code = request.getParameter("code");
                    registerCodeServer.deleteCode(code);
                    response.sendRedirect("manager.jsp#code");
                    break;
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
